//
//  BZUCDataBaseManager.m
//  BZUCSDK
//
//  Created by 郭艺伟 on 2017/10/10.
//  Copyright © 2017年 郭艺伟. All rights reserved.
//

#import "BZUCDataBaseManager.h"
#import "BZUCDataBase.h"


@implementation BZUCDataBaseManager


#pragma mark 更新用户

/**
 异步跟新用户

 @param user UCUser模型
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)updateUserAsync:(BZUCUser *)user
               success:(void (^)(BOOL bSucced))success
               failure:(void (^)(NSError *error))failure{
    
    dispatch_queue_t zzfQueue = dispatch_queue_create("com.bz.zzf.dbQueue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(zzfQueue, ^{
        
        NSError *error = nil;
        
        BOOL sucessed  = [self updateUserSync:user outError:&error];
        
        if (!error && success) {
            success(sucessed);
        }else{
            if (failure) {
                failure(error);
            }
        }
    });
    
}


/**
 同步更新用户

 @param user UCUser模型
 @param outError <#outError description#>
 @return <#return value description#>
 */
+ (BOOL)updateUserSync:(BZUCUser *)user
              outError:(NSError *__autoreleasing *)outError{
    
    __block BOOL success = NO;
    
    if (user) {
        
        FMDatabaseQueue *dbQueue = [[BZUCDataBase shareDataBase] getDatabaseQueue];
        
        [dbQueue inDatabase:^(FMDatabase *db) {
            
            success = [db executeUpdate:@"INSERT OR REPLACE INTO userTable (customerId,nickname,password,phone,realName,sectId,sectName,status,type,username,portrait,sessionId,backgroundUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",@(user.customerId),user.nickname,user.password,user.phone,user.realName,@(user.sectId),user.sectName,@(user.status),@(user.type),user.username,user.portrait,user.sessionId,user.backgroundUrl];
            
            if (success) {
                success = [db executeUpdate:@"DELETE FROM loginUserTable"];
                if (success) {
                    NSTimeInterval now     = [[NSDate date]timeIntervalSince1970];
                    NSString *loginTime    = [NSString stringWithFormat:@"%.0f",now];
                    NSString *expireTime   = [NSString stringWithFormat:@"%.0f",(now+7*24*3600)];
                    success = [db executeUpdate:@"INSERT INTO loginUserTable (customerId,loginAccount,password,loginTime,expireTime) VALUES (?,?,?,?,?)",@(user.customerId),user.username,user.password,loginTime,expireTime];
                }
            }
        }];
    }
    return success;
}


/**
 更新当前用户超时时间

 @param expireTime <#expireTime description#>
 @param outError <#outError description#>
 @return <#return value description#>
 */
+ (BOOL)updateCurrentUserExpireTimeByParamSync:(NSString *)expireTime
                                      outError:(NSError *__autoreleasing *)outError{
    
    
    FMDatabaseQueue *dbQueue = [[BZUCDataBase shareDataBase] getDatabaseQueue];
    
    
    __block BOOL success = NO;
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        success = [db executeUpdate:@"UPDATE loginUserTable SET expireTime ='%@'",expireTime];
    }];
    
    return success;
}



/**
 获取当前登录的用户

 @param outError 错误信息
 @return BZUCUser 模型
 */
+ (BZUCUser *)queryCurrentLoginUserWithError:(NSError *__autoreleasing *)outError{
    
    
    FMDatabaseQueue *dbQueue = [[BZUCDataBase shareDataBase]getDatabaseQueue];
    
    BZUCUser *user = [BZUCUser shareInstance];
    [user clean];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *result = [db executeQuery:@"SELECT * FROM loginUserTable"];
        
        NSMutableArray *datas = [[NSMutableArray alloc]init];
        
        while ([result next]) {
            
            long long customerId = [result longLongIntForColumn:@"customerId"];
            
            user.expireTime   = [result stringForColumn:@"expireTime"];
            
            [datas addObject:@(customerId)];
        }
        [result close];
        
        if ([datas count] == 1) {
            
            FMResultSet * result = [db executeQuery:@"SELECT * FROM userTable WHERE customerId = ? ",[datas firstObject]];
            
            while ([result next]) {
                
                user.customerId = [result longForColumn:@"customerId"];
                user.username   = [result stringForColumn:@"username"];
                user.nickname   = [result stringForColumn:@"nickname"];
                user.realName   = [result stringForColumn:@"realName"];
                user.phone      = [result stringForColumn:@"phone"];
                user.portrait   = [result stringForColumn:@"portrait"];
                user.type       = [result intForColumn:@"type"];
                user.sectName   = [result stringForColumn:@"sectName"];
                user.status     = [result intForColumn:@"status"];
                user.sectId     = [result intForColumn:@"sectId"];
                user.password   = [result stringForColumn:@"password"];
                user.sessionId  = [result stringForColumn:@"sessionId"];
                user.backgroundUrl = [result  stringForColumn:@"backgroundUrl"];
            }
            
            [result close];
            
        }else{
            if (outError) {
                *outError = [NSError errorWithDomain:@"com.bz.zzf" code:0 userInfo:@{NSLocalizedDescriptionKey :@"数据库系统紊乱"}];
            }
        }
    }];
    return user;
}


/**
 异步删除当前登录的账号

 @return 是否删除成功
 */
+ (BOOL)deleteLoginUserlSync{
    
    
    FMDatabaseQueue *dbQueue  = [[BZUCDataBase shareDataBase] getDatabaseQueue];
    
    __block BOOL success = NO;
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        
        success = [db executeUpdate:@"DELETE FROM loginUserTable"];
        
    }];
    
    
    return success;
}


@end
